import json
import time
import subprocess
from config.config import PUBLIC_ENV
from crawler.connection import redis_conn
from crawler.monitor.container_monitor import ContainerMonitor


class IdleLogRecorder(object):
    def __init__(self):
        self.hostname = ''
        self.env = PUBLIC_ENV

    def get_hostname(self):
        if not self.hostname:
            for i in range(10):
                a, self.hostname = subprocess.getstatusoutput('hostname')
                if self.hostname:
                    break
                time.sleep(1)

    def record_idle_log(self, spider, project_type, step="spider_open"):
        """记录idle日志"""
        self.get_hostname()
        spider_name = spider.name + '_' + project_type
        monitor_dict = {
            'service': spider_name,
            'step': step,
            'state': 200,
            'hostname': self.hostname,
            'env': self.env,
            'logTime': int(time.time()),
        }
        monitor_key = spider_name + '|' + self.hostname
        redis_conn.hset('crawler_container_monitor', monitor_key, json.dumps(monitor_dict))
        spider.logger.info('Record Monitor Log : {}'.format(json.dumps(monitor_dict)))


if __name__ == '__main__':
    idle_logger = IdleLogRecorder()
